package cn.pconline.autoclub.service;

import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import com.alibaba.fastjson.JSONObject;
import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaReply;
import cn.pconline.autoclub.entity.Photo;
import cn.pconline.autoclub.entity.PhotoReply;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;

/**
 * @author zhouruxuan
 * @date 2015年2月27日 下午4:09:42
 */
public class PhotoReplyService {

	@Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PagerService pagerService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ClubService clubService;
    private static final Logger log = LoggerFactory.getLogger(PhotoReplyService.class);
    
    private static final int DEFAULT_AUTHORPHOTO_SIZE = 50;//作者头像50X50
    /**是图片评论**/
    private static final int IS_PHOTO_REPLY = 1; 
    /**
     * 创建评论
     * @param photoReply
     * @return
     */
    public long createPhotoReply(PhotoReply photoReply) {
    	return geliDao.create(photoReply);
    }
    
    /**
     * 更新评论总数，可传正数和负数
     * @param photoId
     * @param albumId
     * @param number
     * @return
     */
    public long updatePhotoClunt(long photoId, long albumId, int number) {
    	Photo photo = albumService.getPhotoById(photoId, albumId);
    	if(photo == null) {
    		return 0;
    	} 
    	long postCount = photo.getPostCount();
    	photo.setPostCount(postCount + number);
    	return geliDao.update(photo, "post_count");
    }
    
    /**
     * 获取某一条评论信息
     * @param photoReplyId
     * @param photoId
     * @return
     */
    public PhotoReply findPhotoReplyById(long photoReplyId, long photoId) {
    	try {
            if (photoReplyId < 1) {
                return null;
            }
            return geliDao.find(PhotoReply.class, photoId, photoReplyId);
        } catch (DataAccessException e) {
            return null;
        }
    }
    
    /**
     * 获取照片评论列表
     * @param photoId
     * @param descType
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<PhotoReply> pagerPhotoReplyByPhotoId(long photoId, int descType, int pageNo, int pageSize) {
    	SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select photo_reply_id from ").appendSql(geliOrm.getTableName(PhotoReply.class, photoId));
        sql.appendSql(" where photo_id=").appendValue(photoId);
        sql.appendSql(" and status != ").appendValue(PhotoReply.STATUS_DELETE);
        if (descType == 1) {//倒序
            sql.appendSql(" order by create_at desc");
        }
        if (descType == 0) {//顺序
            sql.appendSql(" order by create_at asc");
        }
        try {
            return pagerService.pager(PhotoReply.class, photoId, sql, pageNo, pageSize);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
    
    /**
     * 删除评论
     * @param phtoReplyId
     * @param photoId
     * @return
     */
    public long deletePhotoReply(long phtoReplyId, long photoId) {
        try {
            PhotoReply reply = geliDao.find(PhotoReply.class, photoId, phtoReplyId);
            reply.setStatus(DynaReply.STATUS_DELETE);
            return geliDao.update(reply, "status");
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
    }
    
    /**
     * 修改图片评论的内容的审核状态
     * @param photo
     * @param photoReply
     * @param status
     * @return
     */
    public long censorPhotoReply(Photo photo,PhotoReply photoReply,int status){
    	if(photoReply==null){
    		return 0;
    	}
    	int count = 0;
    	 int oldStatus = photoReply.getStatus();
    	 if(oldStatus!=status){	//状态不一样时执行
    		 photoReply.setStatus( status );
    		 count = geliDao.update(photoReply, "status");
    		 if(count>0 && photo!=null){
    			 if(status == PhotoReply.STATUS_NORMAL){
    				 photo.setPostCount(Math.max(photo.getPostCount() + 1, 0));
    			 }else if(status == PhotoReply.STATUS_DELETE){
    				 photo.setPostCount(Math.max(photo.getPostCount() - 1, 0));
    			 }
    			 geliDao.update( photo, "post_count");
    		 }
    	 }
    	 return count;
    	
    }
    
    /**
     * 发送消息到BIP，针对图片评论
     * @param photoReply
     * @param photo
     */
    public void setJson4BipToListReply(PhotoReply photoReply,Photo photo){
    	int typeId;
    	long senderId = photoReply.getCreateBy();//发送者即回复人
    	long receiverId = photoReply.getPostToUserId();//接收者即被回复人
    	long receiverId2 = photo.getCreateBy();			//图片创建者
    	long toReplyId = photoReply.getPostToPhontoReplyId();	//被回复的评论id（0代表直接评论图片）
    	boolean isSend = false;		//是否已发送过评论者（用于区分当评论者与图片创建者一样的时候，避免发两次）
    	String url = getPhotoUrl(photo);
    	if(toReplyId>0){	//发送到回复图片的评论者
    		typeId = systemConfig.getReplyMyPhotoReplyTyle();
    		if (senderId != receiverId){
    		 isSend = true;
       		 JSONObject jsonReply = setJson4Reply(photoReply);
       		 jsonReply.put("url", url);//图片终端页
    		 jsonReply.put("toReplyId", toReplyId);//被回复ID
    		 jsonReply.put("toReplyUserName", userService.getNickNameByUserId(receiverId));
             jsonReply.put("toReplyContent", photoReply.getContent());//被回复内容
             jsonReply.put("urlBig", photo.getUrl700x());
             jsonReply.put("urlSmall", photo.getUrl144x144());
             jsonReply.put("createBy", receiverId2);//图片创建者ID
             messageService.send(typeId, senderId, receiverId, jsonReply);//过滤发信息给自己
    		}
    	}else{		//评论图片
    		typeId = systemConfig.getReplyMyPhotoType();
    		
    	}
        //发送通知到图片的创建者
        if (senderId != receiverId2 && (receiverId != receiverId2 || !isSend)) {
            JSONObject jsonPhoto = setJson4Reply(photoReply);
            jsonPhoto.put("url", url);//图片终端页
            jsonPhoto.put("toReplyId", photo.getPhotoId());//图片ID
            jsonPhoto.put("toReplyUserName", userService.getNickNameByUserId( photo.getCreateBy())); //
            jsonPhoto.put("toReplyContent", photo.getName());//被回复内容
            jsonPhoto.put("urlBig", photo.getUrl700x());
            jsonPhoto.put("urlSmall", photo.getUrl144x144());
            jsonPhoto.put("createBy", receiverId2);//图片创建者ID
            messageService.send(typeId, senderId, receiverId2, jsonPhoto);//过滤发信息给自己
        }
    	
    }
    
    /**
     * 获取图片终端页
     * @param photo
     * @return
     */
    private String getPhotoUrl(Photo photo){
    	long albumId = photo.getAlbumId();
    	Album album = albumService.getAlbumById( albumId );
    	if(album ==null )return "";
    	Club club = clubService.getClub( album.getClubId());
    	if(club==null) return "";
    	return systemConfig.getRoot() +"/"+club.getClubUrl()+"/album/a"+albumId+"-"+photo.getPhotoId()+"-show/";
    }
    
    /**
     * 组装图片评论json
     * @param photoReply
     * @return
     */
    private JSONObject setJson4Reply(PhotoReply photoReply){
    	JSONObject json = new JSONObject();
        json.put("replyType", DynaInfo.TYPE_PICTURE); //动态类型,图片动态
        json.put("isPhotoReply", IS_PHOTO_REPLY);	// 1 代表是图片评论
        json.put("targetId", photoReply.getPhotoId());	//图片id
        json.put("albumId", photoReply.getAlbumId()); //相册id
        json.put("replyId", photoReply.getPhotoReplyId());//回复ID
        json.put("replyContent", photoReply.getContent());//回复内容
        json.put("replyUserId", photoReply.getCreateBy());//回复人ID
        json.put("replyUserName", userService.getNickNameByUserId(photoReply.getCreateBy()));//回复人昵称
        json.put("replyUserImg", WebUtils.face(photoReply.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));//回复人头像
        
        json.put("time", photoReply.getCreateAt());
        return json;
    }
    
    
    
}
